package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author 96558
 * @Date 2021/1/11 21:06
 * @Version 1.0
 **/
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 根据状态查询需要认证相关的用户信息
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.执行查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper();

        /**状态
         *0待审核
         *1审核失败
         *9审核通过
         * */
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(page, wrapper);
        //3。结果封装
        // 3 返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal(), pageResult.getRecords());
        return pageResponseResult;
    }

    /**
     * 审核认证
     *
     * @param dto
     * @param status 2审核失败   9审核成功
     * @return
     */
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户当前的合法性
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId, dto.getId())
                .ne(ApUserRealname::getStatus, 9)
        );
        if (apUserRealname == null) {
            CustException.cust(AppHttpCodeEnum.APUSERREALNAME_DATANOTEXIST_ERROR);
        }

        //APUser  Id
        Integer apUserId = apUserRealname.getUserId();
        ApUser apUser = apUserMapper.selectOne(
                Wrappers.<ApUser>lambdaQuery()
                        .eq(ApUser::getId, apUserId)
                        .eq(ApUser::getStatus, 0)
        );

        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //3.修改当前ApUserRealname的状态
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotEmpty(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //4.如果出传递status审核通过
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //4.1Feign创建  自媒体人账号
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser == null) {
                CustException.cust(AppHttpCodeEnum.WMUSER_ADD_ERROR);
            }
            //4.2Feign创建   文章作者账号
            Boolean flag = createApAuthor(wmUser);
            if (!flag) {
                CustException.cust(AppHttpCodeEnum.APAUTHOR_ADD_ERROR);
            }

            //5.修改apUser  flag为自媒体人
            apUser.setFlag((short)1);
            apUserMapper.updateById(apUser);

        }


        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /*
     * 创建文章作者信息
     *
     * */
    @Autowired
    ArticleFeign articleFeign;

    private Boolean createApAuthor(WmUser wmUser) {
        //1.查询文章作者信息
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setWmUserId(wmUser.getId());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setType(2);
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());

            ResponseResult result = articleFeign.save(apAuthor);
            if (result.getCode() == 0) {
                return true;
            }
        }
        return false;
    }
    /*
     * 创建WmUser自媒体账号
     * dto
     * apUser
     * */

    @Autowired
    WemediaFeign wemediaFeign;

    private WmUser createWmUser(AuthDto dto, ApUser apUser) {

        //1.查询自媒体人
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

            wmUser = wemediaFeign.save(wmUser);
            if (wmUser.getId() != null) {
                return wmUser;
            }

        }
        return null;
    }


}
